package com.xcdh.orm.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.xcdh.commons.utils.DataSourceContextHolder;
import com.xcdh.orm.config.DataSourceCache;
import com.xcdh.orm.entity.OrmDataSource;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.support.DefaultPointcutAdvisor;

/**
 * DbMethodInterceptor
 * Created by wjg on 2023/11/30.
 */
public class DbServiceProxy implements MethodInterceptor {

    private String serviceId ;

    private Object target ;
    public DbServiceProxy(String serviceId , Class service ){
        this.serviceId = serviceId ;
        String serviceName = service.getSimpleName();
        DataSourceCache dataSourceCache = SpringUtil.getBean(DataSourceCache.class);
        OrmDataSource dataSource = dataSourceCache.getDataSource(serviceId) ;
        this.target = SpringUtil.getBean(String.format("%s%s",dataSource.getDbName(),serviceName)) ;
    }





    public static <T> T cretedDDLService(String serviceId , Class<T> tClass){
        DbServiceProxy dbServiceProxy = new DbServiceProxy(serviceId , tClass) ;
        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        proxyFactoryBean.setTarget(dbServiceProxy.target);
        proxyFactoryBean.addAdvisor(new DefaultPointcutAdvisor(dbServiceProxy));
        return (T) proxyFactoryBean.getObject();
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        try{
            DataSourceContextHolder.set(serviceId);
            return invocation.proceed() ;
        }finally {
            DataSourceContextHolder.clear();
        }
    }
}
